#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include "msgq.h"
#include "tools.h"

Ctos ctos,ctos_other;
Stoc stoc;

void transf_acc(void)
{
	char path1[PATH_MAX],path2[PATH_MAX];
	Account acc1,acc2;
	sprintf(path1,"%s/%u",ACC_PATH,ctos.acc.id);
	sprintf(path2,"%s/%u",ACC_PATH,ctos_other.acc.id);
	
	pf("acc path1:%s\n",path1);
	pf("acc path2:%s\n",path2);
	int fd1 = open(path1,O_RDWR);
	int fd2 = open(path2,O_RDWR);
	
	if(ERROR == fd2)
	{
		perror("open acc");
		sprintf(stoc.str,"对不起，该用户不存在");
	}
	else
	{
		read(fd1,&acc1,sizeof(Account));
		read(fd2,&acc2,sizeof(Account));
		
		if(ctos.acc.money > acc1.money)
		{
			sprintf(stoc.str,"对不起，您的账户余额不足,余额为:%f",acc1.money);
		}
		else
		{
			acc1.money -= ctos_other.acc.money;
			acc2.money += ctos_other.acc.money;
			
			lseek(fd1,SEEK_SET,0);
			write(fd1,&acc1,sizeof(Account));
			lseek(fd2,SEEK_SET,0);
			write(fd2,&acc2,sizeof(Account));
				
			sprintf(stoc.str,"恭喜您转账成功,您的账户余额为:%f",acc1.money);
		}
	}
	// 返回开户成功信息
	stoc_send(&stoc);
}

int main()
{
	init_msgq();
	for(;;)
	{
		ctos_recv(&ctos,TYPE_TRANSF);
		ctos_recv(&ctos_other,TYPE_TRANSF);
		stoc.type = ctos.pid;
		transf_acc();
	}
}